package com.action.gulimall.product.config;

import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author sl shilun217@qq.com
 * @Deacription spring cache配置类
 * @date 2021/06/20/20:28
 **/
@EnableCaching
@Configuration
public class SpringCacheConfig {

    A a;

    //@Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }

    //测试ObjectProvider，
    @Bean
    public B getB(ObjectProvider<A> a){
        B b=new B();
        A ifAvailable = a.getIfAvailable();
        //当容器中存在A的实例时，这里ifAvailable为容器中的实例，否则为null
        if(ifAvailable!=null){
            b.setAge(ifAvailable.age);
            b.setName(ifAvailable.name);
        }
        System.out.println(b.toString());
        return b;
    }

    @Bean
    public A getA(){
        return new A();
    }
}
@ToString
@Data
class A {
    String name;
    Integer age;

    A(){
        age=29;
        name="shilun";
    }
}
@ToString
@Data
class B {
    String name;
    Integer age;
}